package com.pzhuweb.sgblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pzhuweb.sgblog.domain.entity.LoginUser;
import com.pzhuweb.sgblog.domain.entity.User;
import com.pzhuweb.sgblog.mapper.UserMapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @Author 鄧浩奇
 * @Classname UserDetailsServiceImpl
 * @Description TODO
 * @Date 2023/5/11 19:20
 **/

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);

        // 根据用户名查询用户信息,要保证用户名唯一
        User user = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在!");
        }
        // 判断是否查到用户
        return new LoginUser(user);
    }
}
